#Boa:Frame:Frame1

import wx
import wx.grid
import utiles
import consultasBD
from decimal import Decimal

GRIS = ( 220, 220, 220, 255)
NEGRO = ( 0, 0, 0, 255)
VERDENEGRO = ( 47, 79, 79, 255)

def create(parent):
    return Frame1(parent)

[wxID_FRAME1, wxID_FRAME1BUTTON1, wxID_FRAME1BUTTON2, wxID_FRAME1BUTTON3, 
 wxID_FRAME1BUTTON4, wxID_FRAME1COMBOBOX1, wxID_FRAME1DATEPICKERCTRL1, 
 wxID_FRAME1DATEPICKERCTRL2, wxID_FRAME1GRID1, wxID_FRAME1PANEL1, 
 wxID_FRAME1STATICTEXT1, wxID_FRAME1STATICTEXT2, wxID_FRAME1STATICTEXT3, 
] = [wx.NewId() for _init_ctrls in range(13)]

class Frame1(wx.Frame):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
              pos=wx.Point(26, 66), size=wx.Size(908, 444),
              style=wx.DEFAULT_FRAME_STYLE, title='Ventas detallada')
        self.SetClientSize(wx.Size(900, 417))

        self.panel1 = wx.Panel(id=wxID_FRAME1PANEL1, name='panel1', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(900, 417),
              style=wx.TAB_TRAVERSAL)

        self.staticText1 = wx.StaticText(id=wxID_FRAME1STATICTEXT1,
              label='Vendedora', name='staticText1', parent=self.panel1,
              pos=wx.Point(16, 8), size=wx.Size(53, 13), style=0)

        self.comboBox1 = wx.ComboBox(choices=[], id=wxID_FRAME1COMBOBOX1,
              name='comboBox1', parent=self.panel1, pos=wx.Point(16, 24),
              size=wx.Size(130, 21), style=0, value='')
        self.comboBox1.SetLabel('')

        self.staticText2 = wx.StaticText(id=wxID_FRAME1STATICTEXT2,
              label='Fecha desde', name='staticText2', parent=self.panel1,
              pos=wx.Point(160, 8), size=wx.Size(61, 13), style=0)

        self.datePickerCtrl1 = wx.DatePickerCtrl(id=wxID_FRAME1DATEPICKERCTRL1,
              name='datePickerCtrl1', parent=self.panel1, pos=wx.Point(160, 24),
              size=wx.Size(80, 21), style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)

        self.staticText3 = wx.StaticText(id=wxID_FRAME1STATICTEXT3,
              label='Fecha hasta', name='staticText3', parent=self.panel1,
              pos=wx.Point(248, 8), size=wx.Size(59, 13), style=0)

        self.datePickerCtrl2 = wx.DatePickerCtrl(id=wxID_FRAME1DATEPICKERCTRL2,
              name='datePickerCtrl2', parent=self.panel1, pos=wx.Point(248, 24),
              size=wx.Size(80, 21), style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)

        self.button1 = wx.Button(id=wxID_FRAME1BUTTON1, label='Buscar',
              name='button1', parent=self.panel1, pos=wx.Point(344, 24),
              size=wx.Size(75, 23), style=0)
        self.button1.Bind(wx.EVT_BUTTON, self.OnBuscar, id=wxID_FRAME1BUTTON1)

        self.button2 = wx.Button(id=wxID_FRAME1BUTTON2, label='Limpiar',
              name='button2', parent=self.panel1, pos=wx.Point(424, 24),
              size=wx.Size(75, 23), style=0)
        self.button2.Bind(wx.EVT_BUTTON, self.OnLimpiar, id=wxID_FRAME1BUTTON2)

        self.button4 = wx.Button(id=wxID_FRAME1BUTTON4, label='Imprimir',
              name='button4', parent=self.panel1, pos=wx.Point(712, 24),
              size=wx.Size(75, 23), style=0)
        self.button4.Bind(wx.EVT_BUTTON, self.OnImprimir, id=wxID_FRAME1BUTTON4)

        self.button3 = wx.Button(id=wxID_FRAME1BUTTON3, label='Salir',
              name='button3', parent=self.panel1, pos=wx.Point(808, 24),
              size=wx.Size(75, 23), style=0)
        self.button3.Bind(wx.EVT_BUTTON, self.OnSalir, id=wxID_FRAME1BUTTON3)

        self.grid1 = wx.grid.Grid(id=wxID_FRAME1GRID1, name='grid1',
              parent=self.panel1, pos=wx.Point(16, 56), size=wx.Size(872, 344),
              style=0)

    def __init__(self, parent):
        self._init_ctrls(parent)
        self.llenarComboUsuarios()
        self.comboBox1.SetFocus()
        self.crearGrillas()

    def llenarComboUsuarios(self):
        r1 = "SELECT idvendedora,nombre FROM vendedoras WHERE sucursal<>'0' "
        r2 = "ORDER BY nombre,sucursal"
        sql = r1+r2
        resultado = consultasBD.ordenCruda(sql)
        self.comboBox1.Append("todos")
        for item in resultado:
            self.comboBox1.Append(item[1]+" / "+str(item[0]))
        self.comboBox1.SetLabel("todos")
        self.comboBox1.SetSelection(0)

    def crearGrillas(self):
        self.grid1.CreateGrid(1,11)
        self.ajustarAnchoColumnas()
        self.grid1.EnableEditing(False)
        self.grid1.Refresh()

    def ajustarAnchoColumnas(self):
        for y in xrange(self.grid1.GetNumberCols()):
            self.grid1.AutoSizeColumn(y,True)

    def OnSalir(self, event):
        self.Close()

    def obtenerFacturasClientes(self):
        vendedora = self.comboBox1.GetLabel()
        aux1 = self.datePickerCtrl1.GetLabel()
        aux1 = aux1.replace("/","-")
        fechaInicial = utiles.invertirFecha(aux1)+" 00:00:00"
        aux2 = self.datePickerCtrl2.GetLabel()
        aux2 = aux2.replace("/","-")
        fechaFinal = utiles.invertirFecha(aux2)+" 23:59:59"
        condicion = ""
        if self.comboBox1.GetLabel()!="todos":
            aux1 = self.comboBox1.GetLabel()
            nombre,codigo = aux1.split(" / ")
            condicion = " AND usuario='"+codigo+"' "
        r1 = "SELECT idventa,nrofactura,fecha,idcliente,descuento, \n"
        r2 = "       totalfactura,usuario,idformaticket \n"
        r3 = "FROM ventas \n"
        r4 = "WHERE fecha BETWEEN '"+fechaInicial+"' AND '"+fechaFinal+"' \n"
        r5 = condicion+" ORDER BY fecha DESC "
        sql = r1+r2+r3+r4+r5
        return consultasBD.ordenCrudaDict(sql)

    def obtenerItemsFacturasClientes(self,idventa):
        r1 = "SELECT ptc,descri,talle,color,cantidad,preciolista,descuento,preciofinal "                        
        r2 = "FROM ventastieneproductos WHERE idticket='"+idventa+"' "
        consultaSQL = r1+r2
        return consultasBD.ordenCrudaDict(consultaSQL)

    def obtenerCodSussanItem(self,ptc=""):
        consultaSQL = "SELECT codsussan FROM producto_talle_color WHERE id='"+str(ptc)+"'"
        resultado = consultasBD.ordenCrudaDict(consultaSQL)
        if resultado is None:
            return "-"
        else:
            return resultado

    def obtenerNombreVendedora(self,vendedora):
        consultaSQL = "SELECT nombre FROM vendedoras WHERE idvendedora='"+str(vendedora)+"'"
        return consultasBD.ordenCruda(consultaSQL)

    def obtenerNombreCliente(self,idcliente):
        consultaSQL = "SELECT nombre FROM cliente WHERE idcliente='"+str(idcliente)+"'"
        return consultasBD.ordenCruda(consultaSQL)

    def obtenerPagoEfectivo(self,idventa=""):
        r1 = "SELECT idventa,idformapagos,descrivalor,monto,cuotas,nrorecibo "
        r2 = "FROM ventastienepagos WHERE idventa='"+str(idventa)+"'"
        consultaSQL = r1 + r2
        return consultasBD.ordenCrudaDict(consultaSQL)

    def obtenerPagoCtasCtes(self,idventa=""):
        r1 = "SELECT idventa,vencimiento,idformapagos,descripcion,cuota,montocuota,montopagado,idrecibo "
        r2 = "FROM vtas_ctasctes WHERE idventa='"+str(idventa)+"' AND cuota<>'0' "
        consultaSQL = r1 + r2
        return consultasBD.ordenCrudaDict(consultaSQL)

    def facturaEncabezado(self,renglon,item):
        #datos cabecera: factura, fecha
        self.grid1.AppendRows(1)
        self.grid1.SetCellValue(renglon, 0, "Fecha")
        fecha = str(item['fecha'])
        fecha = fecha[8:10]+"-"+fecha[5:7]+"-"+fecha[0:4]
        self.grid1.SetCellValue(renglon, 1, fecha)
        self.grid1.SetCellValue(renglon, 2, "Factura/NC: "+str(item['nrofactura'])+" Ticket: "+str(item['idventa']))
        self.grid1.SetCellValue(renglon, 3, "$")
        self.grid1.SetCellAlignment(renglon, 3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellValue(renglon, 4, str(item['totalfactura']))
        for col in xrange(11):
            self.grid1.SetCellBackgroundColour(renglon, col, GRIS)

    def facturaCuerpoEncabezado(self,renglon):
        colortexto = VERDENEGRO
        self.grid1.AppendRows(1)
        self.grid1.SetCellValue(renglon, 0,"PTC")
        self.grid1.SetCellTextColour(renglon, 0, colortexto)
        self.grid1.SetCellValue(renglon, 1,"CODIGO")
        self.grid1.SetCellTextColour(renglon, 1, colortexto)
        self.grid1.SetCellValue(renglon, 2,"DESCRIPCION")
        self.grid1.SetCellTextColour(renglon, 2, colortexto)
        self.grid1.SetCellValue(renglon, 3,"Talle")
        self.grid1.SetCellTextColour(renglon, 3, colortexto)
        self.grid1.SetCellAlignment(renglon, 3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellValue(renglon, 4,"Color")
        self.grid1.SetCellTextColour(renglon, 4, colortexto)
        self.grid1.SetCellAlignment(renglon, 4, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellValue(renglon, 5,"Cant.")
        self.grid1.SetCellTextColour(renglon, 5, colortexto)
        self.grid1.SetCellAlignment(renglon, 5, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellValue(renglon, 6,"Precio")
        self.grid1.SetCellTextColour(renglon, 6, colortexto)
        self.grid1.SetCellAlignment(renglon, 6, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellValue(renglon, 7,"Subtotal")
        self.grid1.SetCellTextColour(renglon, 7, colortexto)
        self.grid1.SetCellAlignment(renglon, 7, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellValue(renglon, 8,"Desc %")
        self.grid1.SetCellTextColour(renglon, 8, colortexto)
        self.grid1.SetCellAlignment(renglon, 8, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellValue(renglon, 9,"TOTAL")
        self.grid1.SetCellTextColour(renglon, 9, colortexto)
        self.grid1.SetCellAlignment(renglon, 9, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellValue(renglon, 10,"Modista")
        self.grid1.SetCellAlignment(renglon, 10, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)

    def facturaCuerpo(self,renglon,item,codsussan="-"):
        #datos cuerpo: ptc,codigo,descripcion,talle,color,cant,unitario,subtotal,desc,total,modista
        self.grid1.AppendRows(1)
        self.grid1.SetCellValue(renglon, 0,str(item['ptc']))
        self.grid1.SetCellValue(renglon, 1,str(codsussan))
        self.grid1.SetCellValue(renglon, 2,str(item['descri']))
        self.grid1.SetCellValue(renglon, 3,str(item['talle']))
        self.grid1.SetCellAlignment(renglon, 3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellValue(renglon, 4,str(item['color']))
        self.grid1.SetCellAlignment(renglon, 4, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellValue(renglon, 5,str(item['cantidad']))
        self.grid1.SetCellAlignment(renglon, 5, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellValue(renglon, 6,str(item['preciolista']))
        self.grid1.SetCellAlignment(renglon, 6, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellValue(renglon, 7,str(item['cantidad']*item['preciolista']))
        self.grid1.SetCellAlignment(renglon, 7, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellValue(renglon, 8,str(item['descuento']))
        self.grid1.SetCellAlignment(renglon, 8, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellValue(renglon, 9,str(item['preciofinal']))
        self.grid1.SetCellAlignment(renglon, 9, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)

    def pagosEncabezado(self,renglon):
        colortexto = VERDENEGRO
        self.grid1.AppendRows(1)
        self.grid1.SetCellValue(renglon, 1,"Nro Recibo")
        self.grid1.SetCellTextColour(renglon, 1, colortexto)
        self.grid1.SetCellValue(renglon, 2,"DESCRIPCION")
        self.grid1.SetCellTextColour(renglon, 2, colortexto)
        self.grid1.SetCellValue(renglon, 3,"Cuotas")
        self.grid1.SetCellAlignment(renglon, 3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellValue(renglon, 4,"$ CUOTA")
        self.grid1.SetCellTextColour(renglon, 4, colortexto)
        self.grid1.SetCellAlignment(renglon, 4, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        
    def pagosDetalle(self,renglon,item):
        self.grid1.AppendRows(1)
        self.grid1.SetCellValue(renglon, 1,str(item['nrorecibo']))
        self.grid1.SetCellValue(renglon, 2,str(item['idformapagos'])+" / "+str(item['descrivalor']))
        self.grid1.SetCellValue(renglon, 3,str(item['cuotas']))
        self.grid1.SetCellAlignment(renglon, 3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellValue(renglon, 4,str(item['monto']))
        self.grid1.SetCellAlignment(renglon, 4, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)

    def renglonVendedora(self,renglon,vendedora,tipo,nombrecliente):
        self.grid1.AppendRows(1)
        self.grid1.SetCellValue(renglon, 1,"Cliente")
        self.grid1.SetCellBackgroundColour(renglon, 1, GRIS)
        self.grid1.SetCellValue(renglon, 2,nombrecliente)
        self.grid1.SetCellBackgroundColour(renglon, 2, GRIS)
##        self.grid1.AppendRows(1)
##        renglon+= 1
##        self.grid1.SetCellValue(renglon, 1,"Vendedora")
##        self.grid1.SetCellBackgroundColour(renglon, 1, GRIS)
##        self.grid1.SetCellValue(renglon, 2,vendedora)
##        self.grid1.SetCellBackgroundColour(renglon, 2, GRIS)
##        self.grid1.SetCellValue(renglon, 3,"Tipo: ")
##        self.grid1.SetCellBackgroundColour(renglon, 3, GRIS)
##        self.grid1.SetCellAlignment(renglon, 3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
##        self.grid1.SetCellValue(renglon, 4,str(tipo))
##        self.grid1.SetCellBackgroundColour(renglon, 4, GRIS)
##        self.grid1.SetCellAlignment(renglon, 4, wx.ALIGN_LEFT, wx.ALIGN_CENTRE)

    def pagosEncabezadoCtaCte(self,renglon):
        colortexto = VERDENEGRO
        self.grid1.AppendRows(1)
        self.grid1.SetCellValue(renglon, 1,"CTA.CTE.")
        self.grid1.SetCellBackgroundColour(renglon, 1, GRIS)
        self.grid1.AppendRows(1)
        renglon = renglon + 1
        self.grid1.SetCellValue(renglon, 1,"Cuota")
        self.grid1.SetCellTextColour(renglon, 1, colortexto)
        self.grid1.SetCellValue(renglon, 2,"Vencimiento / Forma pago")
        self.grid1.SetCellTextColour(renglon, 2, colortexto)
        self.grid1.SetCellValue(renglon, 4,"Monto")
        self.grid1.SetCellTextColour(renglon, 4, colortexto)
        self.grid1.SetCellAlignment(renglon, 4, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)

    def pagosDetalleCtaCte(self,renglon,item):
        self.grid1.AppendRows(1)
        self.grid1.SetCellValue(renglon, 1,str(item['cuota']))
        self.grid1.SetCellValue(renglon, 2,str(item['vencimiento'])+" / "+str(item['idformapagos']))
        self.grid1.SetCellValue(renglon, 4,str(item['montocuota']))
        self.grid1.SetCellAlignment(renglon, 4, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)

    def OnBuscar(self, event):
        renglon = 0
        listadoFacturas = self.obtenerFacturasClientes()
        for factura in listadoFacturas:
            #datos cabecera: factura, fecha
            self.facturaEncabezado(renglon,factura)
            renglon = renglon + 1

            listadoItems = self.obtenerItemsFacturasClientes(str(factura['idventa']))

            self.facturaCuerpoEncabezado(renglon)
            renglon = renglon + 1

            for item in listadoItems:
                #datos cuerpo: ptc,codigo,descripcion,talle,color,cant,unitario,subtotal,desc,total,modista
                codsussan = str(self.obtenerCodSussanItem(item['ptc'])[0]['codsussan'])
                self.facturaCuerpo(renglon,item,codsussan)
                renglon = renglon + 1

            vendedora = self.obtenerNombreVendedora(factura['usuario'])[0][0]
            nombrecliente = self.obtenerNombreCliente(factura['idcliente'])[0][0]
            tipo = str(factura['idformaticket'])
            self.renglonVendedora(renglon,vendedora,tipo,nombrecliente+" / "+factura['idcliente'])
            renglon = renglon + 1

            #datos pie: forma,descripcion,cuotas,valor cuota,total
            listadoPagosEfectivo = self.obtenerPagoEfectivo(str(factura['idventa']))
            if listadoPagosEfectivo is not ():
                self.pagosEncabezado(renglon)
                renglon = renglon + 1
                for item in listadoPagosEfectivo:
                    self.pagosDetalle(renglon,item)
                    renglon = renglon + 1

            listadoPagosCtasCtes = self.obtenerPagoCtasCtes(str(factura['idventa']))
            if listadoPagosCtasCtes is not ():
                self.pagosEncabezadoCtaCte(renglon)
                renglon = renglon + 2
                for item in listadoPagosCtasCtes:
                    self.pagosDetalleCtaCte(renglon,item)
                    renglon = renglon + 1

            #agrega renglon en blanco separador
            renglon = renglon + 1
            self.grid1.AppendRows(1)

        for col in xrange(11):
            self.grid1.AutoSizeColumn(col,True)

        self.grid1.Refresh()

        return

    def OnLimpiar(self, event):
        self.grid1.ClearGrid()
        for fil in xrange(self.grid1.GetNumberRows()):
            self.grid1.DeleteRows()
        self.grid1.AppendRows()
        self.comboBox1.SetSelection(0)
        self.comboBox1.SetFocus()

    def OnImprimir(self, event):
        titulo1 = "DETALLE DE COMPRAS"
        titulo2 = "Vendedora: "+self.comboBox1.GetLabel()
        
        fil = self.grid1.GetNumberRows()
        col = self.grid1.GetNumberCols()
        self.button4.Enable(False)
        self.button4.SetLabel("IMPRIMIENDO")
        utiles.reporte2_html(titulo1,titulo2,fil,col,self.grid1)
        self.button4.SetLabel("Imprimir")
        self.button4.Enable(True)

